/*
 * This file is part of LangMan.
 *
 * LangMan is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * LangMan is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with LangMan.  If not, see <http://www.gnu.org/licenses/>.
 */

package langman.util.languagefile.reader;

import com.google.common.base.CharMatcher;
import com.google.common.base.Charsets;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.io.Files;
import langman.business.data.TranslationException;
import langman.util.announcer.Announcer;
import langman.util.languagefile.commons.TranslationMode;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.util.List;

@SuppressWarnings("TailRecursion")
public class LanguageReader implements AutoCloseable {
    private final Announcer<LanguageReaderEventHandler> announcer = Announcer.to(LanguageReaderEventHandler.class);

    private final BufferedReader reader;

    private final Logger logger = LogManager.getLogger(getClass());

    private int lineCounter;

    private final char[] buffer = new char[1];

    private final String languageName;

    public LanguageReader(File languageFile) throws IOException {
        languageName = languageFile.getName();
        reader = Files.newReader(languageFile, Charsets.UTF_8);
    }

    private TranslationMode translationMode;

    public LanguageReader(BufferedReader bufferedReader) {
        languageName = "STREAM";
        reader = bufferedReader;
    }

    @SuppressWarnings("StatementWithEmptyBody")
    public void readToEnd() throws IOException, TranslationException {

        String line;
        while ((line = readLine()) != null) {
            String trimmedLine = line.trim();

            trimmedLine = removeBomIfNecessary(trimmedLine);
            lineCounter++;

            boolean commentedLine = trimmedLine.startsWith("#");

            String textWithoutComment = CharMatcher.anyOf("#").trimLeadingFrom(trimmedLine).trim();

            boolean hasNoText = textWithoutComment.isEmpty();

            if (hasNoText) {
                continue;
            }

            if (commentedLine) {
                processCommentedLine(textWithoutComment);
            } else {
                processNormalLine(line, trimmedLine);
            }
        }
    }

    private String readLine() throws IOException {
        StringBuilder builder = new StringBuilder();
        while (reader.read(buffer) != -1) {
            char character = buffer[0];
            if (character == 0x0A) {
                return builder.toString();
            }
            builder.append(character);
        }
        return null;
    }

    private String removeBomIfNecessary(String line) {
        if (lineCounter == 0) {
            return line.replace("\uFEFF", "");
        }
        return line;
    }

    private void processNormalLine(CharSequence line, String trimmedLine) throws TranslationException {
        boolean hasText = !trimmedLine.isEmpty();
        if (hasText) {
            List<String> split = Splitter.on("=").splitToList(line);

            if (split.size() >= 2) {
                String keyString = split.get(0).trim();
                String value = Joiner.on("=").join(split.subList(1, split.size())).trim();
                announcer.announce().translationEncountered(keyString, value, translationMode);
            } else {
                logger.warn(String.format("Problem during loading of language %s: line %s:%s could not be split in two!", languageName, lineCounter, line));
            }

            translationMode = null;
        }
    }

    private void processCommentedLine(String textWithoutComment) throws TranslationException {
        TranslationMode mode = TranslationMode.tryParseTranslationMode(textWithoutComment);
        if (mode != null) {
            translationMode = mode;
        } else {
            announcer.announce().categoryChanged(textWithoutComment);
            translationMode = null;
        }
    }


    @Override
    public void close() throws IOException {
        reader.close();
    }

    public void addListener(LanguageReaderEventHandler listener) {
        announcer.addListener(listener);
    }
}
